package com.nowcoder.community.controller;

import com.nowcoder.community.service.Alphaservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("/alpha")
public class alphaController {

    @Autowired
    private Alphaservice alphaservice;

    @RequestMapping("/hello")
    @ResponseBody  //返回普通字符串加的声明
    public String sayHello() {
        return "Hello World";
    }

    @RequestMapping("/data")
    @ResponseBody  //返回普通字符串加的声明
    public String getData() {
        return alphaservice.find();
    }

    /**
     * MVC框架下怎么获得请求对象和响应对象p4,底层实现，比较复杂
     */
    @RequestMapping("/http")
    public void http(HttpServletRequest request, HttpServletResponse response) {
        // 为什么没有返回值了，因为通过response对象可以直接返回内容。
        // 获取请求数据
        System.out.println(request.getMethod());
        System.out.println(request.getServletPath());
        // 请求行是key, values
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            System.out.println(name + ": " + value);
        }
        System.out.println(request.getParameter("code"));

        // 返回响应数据
        response.setContentType("text/html;charset=utf-8");
        try (
                PrintWriter writer = response.getWriter();
                ){
            writer.write("<h1>牛客网</h1>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 简单方式，实现MVC框架下，返回和响应对象，怎么接受，怎么返回
    // GET请求

    // /students?current=1&limit=20

    /**
     * 通过@RequestParam对传入的参数进行更详细的说明
     * @param current
     * @param limit
     * @return
     */
    @RequestMapping(path = "/students", method = RequestMethod.GET)
    @ResponseBody
    public String getStudents(
            @RequestParam(name = "current", required = false, defaultValue = "1") int current,
            @RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {
        System.out.println(current);
        System.out.println(limit);
        return "some students";
    }

    // 还有一种方式，获取数据get，提交数据post，post是浏览器向服务器提交数据的时候使用
    // /student/123
    @RequestMapping(path = "/student/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id) {
        System.out.println(id);
        return "a student";
    }

    //Post请求(隐式)
    @RequestMapping(path = "/student", method = RequestMethod.POST)
    @ResponseBody
    public String saveStudent(String name, int age) {
        System.out.println(name);
        System.out.println(age);
        return "success";
    }

    // 返回响应数据response，响应
    // 响应一个动态的html数据
    // 响应(返回)给浏览器,所以要get，返回html，所以不用加@ResponseBody注解
    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
    public ModelAndView getteacher() {
        ModelAndView mav = new ModelAndView();
        // 模板需要多少个变量，就添加多少个object
        mav.addObject("name", "张三");
        mav.addObject("age", 30);
        // 设置模板路径，名字,不需要写.html
        mav.setViewName("/demo/view");
        return mav;
    }

    // 另一种响应方式
    // 简化不返回modelandView，返回view路径
    // 这种是核心方法dispatchServlet有model的引用，然后直接返回view
    @RequestMapping(path = "/school", method = RequestMethod.GET)
    public String getSchool(Model model) {
        model.addAttribute("name", "北大");
        model.addAttribute("age", 100);
        return "/demo/view";
    }

    // 除了响应html以外，还能响应其他的数据，这是响应JSON数据（响应异步请求）
    // 什么是异步请求？：
    // 注册时，当光标移走之后，判断昵称可不可用并且网页没有被刷新，就是异步请求
    // 网页没有刷新，悄悄访问服务器得到一次结果的时候。
    // Java对象-> JSON字符串 -> JS对象
    // 响应JSON字符串
    // 单个员工
    @RequestMapping(path = "/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmp() {
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 15);
        emp.put("salary", 8000.00);
        return emp;
    }

    // 一组员工
    @RequestMapping(path = "/emps", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getEmps() {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 15);
        emp.put("salary", 8000.00);
        list.add(emp);

        emp = new HashMap<>();
        emp.put("name", "李四");
        emp.put("age", 15);
        emp.put("salary", 10000.00);
        list.add(emp);

        emp = new HashMap<>();
        emp.put("name", "王五");
        emp.put("age", 16);
        emp.put("salary", 1000.00);
        list.add(emp);

        return list;
    }





}
